// pages/address_add_edit/index.js
import {
    getNavigationbar,
    SubmitReLogin,
    ReMallShopping
} from "../../api/index.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        btnType: "add", // 页面类型
        identifyValue: "收货人姓名，18809876543，省市",
        isAddress: false,
        storeAddress: '',
        options: [], // 省市区街道镇列表
        fieldNames: {
            text: 'name',
            value: 'id',
            children: 'children',
        }, // 自定义字段名称
        cascaderVal: "",
        showModal: false,
        formData: {
            id: "", // 地址ID
            truename: "", // 姓名
            phone: "", // 手机号
            province: "", // 省份
            city: "", // 城市
            county: "", // 地区
            town: "", // 城镇
            provinceId: "", // 省份ID
            cityId: "", // 城市ID
            countyId: "", // 地区ID
            townId: "", // 城镇ID
            address: "", // 详细地址
            is_default: "", // 是否默认地址

        },
        province: {
            id: "",
            name: "",
        },
        city: {
            id: "",
            name: "",
        },
        county: {
            id: "",
            name: "",
        },
        town: {
            id: "",
            name: "",
        },
        identify: "" //识别内容
    },
    /**
     * 选择地址回调函数方法
     */
    handleSelAddress() {
        this.setData({
            isAddress: true
        })
    },
    onChangeArea({
        value,
        selectedOptions,
        tabIndex
    }) {
        console.log(value, selectedOptions, tabIndex);
        // value是选中当前列的value(areaId),selectedOptions是选中的数组,tabIndex是选中数组的第几个
        // 需要后台接口返回children数据
        // 拿到数据后，动态添加
        if (selectedOptions[selectedOptions.length - 1].childrenStatus) {
            // 如果选中数组的最后一个的childrenStatus为true,说明它有子级，就掉接口
            areaParentData({
                parentCode: selectedOptions[selectedOptions.length - 1].code // 取得是选中数组里最后一个对象的code
            }).then(res => {
                // 接口返回的数据也就是res.data 赋值给那条数据当children
                this.addTree(selectedOptions, res.data, value)
            })
        }
    },
    addTree(selectedOptions, children, id) {
        selectedOptions.forEach(item => {
            if (item.areaId === id) {
                item.children = children
            }
        })
    },
    /**
     * 选择省市行政区回调函数方法
     * @param {*} e 
     */
    handleSelCascader(e) {
        const {
            value,
            tabIndex,
            selectedOptions
        } = e.detail
        console.log(e.detail, 'value', value)
        let num = tabIndex + 2
        // 遍历当前选中地址区间数组对象
        for (let i = 0; i < selectedOptions.length; i++) {
            if (value == selectedOptions[i].id) {
                // 根据遍历的省级ID执行请求，获取省下级城市数组对象列
                getNavigationbar({
                    // act: "provinceLists",
                    act: "getAddressInfo",
                    type: num++,
                    parentid: value
                }).then(res => {
                    console.log("获取城市列表", res, )
                    if (res) {

                        console.log('tabIndex', tabIndex)
                        switch (tabIndex) {
                            case 0:
                                this.data.options.forEach(item => {
                                    item.children = []
                                    res.forEach(items => {
                                        res.forEach(items => {
                                            items.children = []
                                        })
                                        if (item.id == value) {
                                            item.children.push(items)
                                        }
                                    })
                                })
                                this.data.formData.provinceId = selectedOptions[tabIndex].id
                                this.data.formData.province = selectedOptions[tabIndex].name
                                this.setData({
                                    province: {
                                        id: selectedOptions[tabIndex].id,
                                        name: selectedOptions[tabIndex].name,
                                    }
                                })
                                break;
                            case 1:
                              
                                // this.data.options = this.deepUnique(this.data.options)
                                if (selectedOptions[0].id != 1 && selectedOptions[0].id != 2 && selectedOptions[0].id != 3 && selectedOptions[0].id != 4 && selectedOptions[0].id != 32 && selectedOptions[0].id != 33) {
                                    console.log('1')
                                    this.data.options.forEach(item => {
                                        item.children.forEach(element => {
                                            element.children = []
                                          
                                        });
                                        res.forEach(items => {

                                            res.forEach(items => {
                                             
                                              
                                                if(res.length > 0) {
                                                    items.children = []
                                                }

                                            })
                                            item.children.forEach(element => {
                                             
                                                if (element.id == value) {
                                                    element.children.push(items)
                                                }
                                            });

                                        })
                                    })
                                } else {
                                    console.log('2')
                                    this.data.options.forEach(item => {
                                        item.children.forEach(element => {
                                            element.children = []
                                          
                                        });
                                        res.forEach(items => {

                                            item.children.forEach(element => {
                                                element.children = []
                                                if (element.id == value) {
                                                    element.children.push(items)
                                                }
                                            });

                                        })
                                    })
                                }
                                this.data.formData.cityId = selectedOptions[tabIndex].id
                                this.data.formData.city = selectedOptions[tabIndex].name
                                this.setData({
                                    city: {
                                        id: selectedOptions[tabIndex].id,
                                        name: selectedOptions[tabIndex].name,
                                    }
                                })
                                break
                            case 2:
                                // this.data.options = this.deepUnique(this.data.options)
                                if (res.length > 0) {
                                    console.log('金')
                                    this.data.options.forEach(item => {
                                        res.forEach(items => {

                                            item.children.forEach(element => {
                                                element.children.forEach(elementj => {
                                                    elementj.children = []
                                                    if (elementj.id == value) {
                                                        elementj.children.push(items)
                                                    }
                                                });

                                            });

                                        })
                                    })
                                } else {

                                    this.data.options.forEach(item => {
                                        item.children.forEach(element => {
                                            element.children.forEach((elementj, index) => {
                                                console.log('进', elementj)
                                                // elementj.children.splice(index, 1);
                                                delete elementj.children
                                            });
                                        });
                                    });
                                }
                                this.data.formData.county = selectedOptions[tabIndex].name
                                this.data.formData.countyId = selectedOptions[tabIndex].id
                                this.setData({
                                    county: {
                                        id: selectedOptions[tabIndex].id,
                                        name: selectedOptions[tabIndex].name,
                                    }
                                })
                                break;
                            case 3:
                                this.data.formData.town = selectedOptions[tabIndex].name
                                this.data.formData.townId = selectedOptions[tabIndex].id
                                this.setData({
                                    town: {
                                        id: selectedOptions[tabIndex].id,
                                        name: selectedOptions[tabIndex].name,
                                    }
                                })
                                break;
                        }
                        console.log("tabIndex", this.data.options)
                        this.data.options = this.deepUnique(this.data.options)
                        // 重新赋值
                        this.setData({
                            options: this.data.options,
                        })
                    }
                })
            }
        }
    },
    // 使用递归函数来处理多层嵌套的数组去重
    deepUnique(arr) {
        return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(deepUnique(val)) : acc.concat(val), [])
            .filter((item, index, self) => self.indexOf(item) === index);
    },
    /**
     * 全部选项选择完成后触发
     * @param {*} e 
     */
    handleFinish(e) {
        const {
            selectedOptions,
            value,
        } = e.detail;

        console.log(selectedOptions)
        const storeAddress = selectedOptions
            .map((option) => option.text || option.name).join('');
        this.setData({
            storeAddress,
            cascaderVal: value,
            isAddress: false,
            // formData: {
            //     province: "", // 省份
            //     city: "", // 城市
            //     // county: "", // 地区
            //     // town: "", // 城镇
            //     provinceId: "", // 省份ID
            //     cityId: "", // 城市ID
            //     // countyId: "", // 地区ID
            //     // townId: "", // 城镇ID
            // }
        })
        console.log('借宿', this.data.formData);
    },
    /**
     * switch设置默认地址开关回调函数方法
     * @param {*} e 
     */
    handleDefaultCheck(e) {
        console.log('e', e)
        const {
            value
        } = e.detail
        this.data.formData.is_default = value

    },
    /**
     * 删除表单提交回调函数方法
     */
    handleDelAddress() {
        this.setData({
            showModal: true
        })
    },
    /**
     * 新增编辑表单提交回调函数方法
     * @param {*} e 
     */
    handleSubmit(e) {
        const {
            truename,
            phone,
            storeAddress,
            address,
            is_default,
        } = e.detail.value
        console.log("e.detail.value", e.detail.value)
        if (!truename) return getApp().Tips({
            title: '请输入收件人！'
        });
        if (!phone) return getApp().Tips({
            title: '请输入联系电话！'
        });
        if (!storeAddress) return getApp().Tips({
            title: '请选择所在区域！'
        });
        if (!address) return getApp().Tips({
            title: '请输入详细地址！'
        });
        // 执行添加、编辑请求逻辑
        getNavigationbar({
            act: "addressres",
            type: this.data.btnType,
            id: this.data.formData.id,
            truename: truename,
            phone: phone,
            province: this.data.formData.province,
            city: this.data.formData.city,
            county: this.data.formData.county,
            town: this.data.formData.town,
            provinceId: this.data.formData.provinceId,
            cityId: this.data.formData.cityId,
            countyId: this.data.formData.countyId,
            townId: this.data.formData.townId,
            address: address,
            is_default: this.data.formData.is_default ? '1' : '0',
        }).then(res => {
            console.log(res)
            if (res) {
                if (res.result == 101) {
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: res.msg
                        });
                    });
                } else {
                    let title = '添加成功';
                    if (this.data.formData.id) {
                        title = '编辑成功';
                    }
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: title
                        });
                    });
                    let pages = getCurrentPages(); //获取小程序页面栈
                    let beforePage = pages[pages.length - 2];
                    // beforePage.onReady()
                    wx.navigateBack({
                        delta: 1
                    })
                }
            }
        })
    },
    /**
     * 触发弹窗回调函数方法
     * @param {*} e 
     */
    handleShomModal(e) {
        if (e.detail == 'confirm') {
            getNavigationbar({
                act: "delAddress",
                id: this.data.formData.id,
            }).then(res => {
                if (res) {
                    this.setData({
                        showModal: false
                    })
                    let pages = getCurrentPages(); //获取小程序页面栈
                    let beforePage = pages[pages.length - 2];
                    beforePage.onReady()
                    wx.navigateBack({
                        delta: 1
                    })
                    getApp().Tips({
                        title: '收货地址已删除'
                    })
                }
            })
        } else {
            this.setData({
                showModal: false
            })
        }
    },
    /**
     * 获取省份列表
     * @param {*} Province 
     */
    getHttpProvinceLists() {
        // SubmitReLogin({
        //     act: "provinceLists",
        // }).then(res => {
        //     if (res) {
        //         res.forEach(item => {
        //             item.children = []
        //         })
        //       console.log('获取城市列表', res)
        //         this.setData({
        //             options: res
        //         })
        //     }
        // })
        getNavigationbar({
            // act: "provinceLists",
            act: "getAddressInfo",
            type: 1,

        }).then(res => {
            console.log('res', res)
            if (res) {
                res.forEach(item => {
                    item.children = []
                })
                console.log('获取城市列表', res)
                this.setData({
                    options: res
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.data) {
            const params = JSON.parse(options.data)
            console.log('params', params)
            if (params.type == 'add') {
                this.setData({
                    btnType: params.type,
                })
                this.data.formData.is_default = true
                this.setData({
                    formData: this.data.formData
                })
            } else {
                this.setData({
                    btnType: params.type,
                    formData: {
                        id: params.value.id, // 地址ID
                        truename: params.value.truename, // 姓名
                        phone: params.value.phone, // 手机号
                        province: params.value.province, // 省份
                        city: params.value.city, // 城市
                        county: params.value.county, // 地区
                        town: params.value.town, // 城镇
                        provinceId: params.value.provinceId, // 省份ID
                        cityId: params.value.cityId, // 城市ID
                        countyId: params.value.countyId, // 地区ID
                        townId: params.value.townId, // 城镇ID
                        address: params.value.address, // 详细地址
                        is_default: params.value.is_default == 1 ? true : false, // 是否默认地址
                    },
                    // 编辑状态下拼接地址回显
                    storeAddress: params.value.province + params.value.city + params.value.county + params.value.town
                })
                console.log(this.data.formData)
            }
        }
    },

    handleIdentify() {
        if (this.data.identify) {
            console.log(this.data.identify)
            ReMallShopping({
                act: "address_matching",
                address: this.data.identify
            }).then(res => {
                this.data.formData.truename = res.truename
                this.data.formData.address = res.address
                this.data.formData.city = res.city
                this.data.formData.cityId = res.city_id
                this.data.formData.county = res.county
                this.data.formData.countyId = res.county_id
                this.data.formData.phone = res.phone
                this.data.formData.province = res.province
                this.data.formData.provinceId = res.province_id
                this.data.formData.town = res.town
                this.data.formData.townId = res.town_id
                this.data.storeAddress = res.province + '省' + res.city
                this.setData({
                    formData: this.data.formData,
                    storeAddress: this.data.storeAddress
                })
                console.log('识别', res)
            })
        }







        //   let identifys = this.data.identify.split("，");
        //   if (identifys.length > 0) {
        //     this.data.formData.truename = identifys[0]
        //   }
        //   if (identifys.length > 1) {
        //     this.data.formData.phone = identifys[1]
        //   }
        //   if (identifys.length > 2) {
        //     SubmitReLogin({
        //       act: "provinceLists",
        //     }).then(res => {
        //       let province = res.filter(item => item.name === identifys[2].split('省')[0] + '省')
        //       if (province && province.length > 0) {
        //         this.data.formData.province = province[0].name
        //         this.data.formData.provinceId = province[0].id
        //         let cityName = identifys[2].split('省')[1].split('市')[0] + '市';
        //         SubmitReLogin({
        //           act: "get_city_lists",
        //           id: province[0].id
        //         }).then(res1 => {
        //           if (res1) {
        //             let city = res1.filter(item => item.name === cityName)
        //             this.data.formData.city = city[0].name
        //             this.data.formData.cityId = city[0].id
        //             this.data.storeAddress = province[0].name + city[0].name
        //             this.setData({
        //               formData: this.data.formData,
        //               storeAddress: this.data.storeAddress
        //             })
        //           }
        //         })
        //       }
        //     })
        //     let citys = identifys[2].split('市');
        //     if (citys.length > 1) {
        //       this.data.formData.address = citys[1]
        //     }

        //   }
        //   this.setData({
        //     formData: this.data.formData,
        //     storeAddress: this.data.storeAddress
        //   })
        // }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.getHttpProvinceLists()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})